#include <IDK.hpp>

#include <RenderTarget.hpp>

namespace Core
{
	//-------------------------------------------------------
	// TRenderTarget
	//-------------------------------------------------------
	TRenderTarget::TRenderTarget(const String& name) : Base(), mName(name)
	{
	}

	void TRenderTarget::BindGpuResource(IDK::IRenderState& rndState)
	{
		if(mTarget == NullPtr || mTarget->IsInvalid())
		{
			mTarget = rndState.CreateRenderTarget(
				Get(0)->GetWidth(),
				Get(0)->GetHeight());

			uint index = 0;

			for(Iterator it = Begin(), end = End();
				it!=end;
				++it)
			{
				it->Attach(rndState, index++);
			}
		}
	}

	//-------------------------------------------------------
	// Render
	//-------------------------------------------------------
	bool TRenderTarget::Render(IDK::IRenderState& rndState)
	{
		if(Length() > 0)
		{
			BindGpuResource(rndState);
			rndState.SetRenderTarget(mTarget);
			rndState.ClearBuffers();
		}
		return true;
	}

	//-------------------------------------------------------
	// Rendered
	//-------------------------------------------------------
	void TRenderTarget::Rendered(IDK::IRenderState& rndState)
	{
		if(Length() > 0)
		{
			rndState.SetRenderTarget(NullPtr);
		}
	}

	//-------------------------------------------------------
	// AttachTexture
	//-------------------------------------------------------
	void TRenderTarget::AttachTexture(ref<IDK::IRenderTexture> rndTex)
	{
		Add(rndTex); //add to texture list
	}

	//-------------------------------------------------------
	// AttachDepth
	//-------------------------------------------------------
	void TRenderTarget::AttachDepth(ref<IDK::IRenderTexture> depthTex)
	{
		mDepthTexture = depthTex;
	}

	//-------------------------------------------------------
	// GetRenderTextures
	//-------------------------------------------------------
	IDK::IRenderTarget::RenderTextures TRenderTarget::GetRenderTextures(void)
	{
		return RenderTextures(this);
	}

	//-------------------------------------------------------
	// GetDepthTexture
	//-------------------------------------------------------
	ref<IDK::IRenderTexture> TRenderTarget::GetDepthTexture(void)
	{
		return mDepthTexture;
	}
}